package com.mycompany.app.util.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.springframework.util.Assert;

/**
 * �����ڵ�ǰ�������private/protected��Ա����private/protected�����BeanUtils.
 * ע��,��Ϊ����Ϊ��ǰ������ı�,ͨ��̳л�õ�protected�������ܷ���,
 * ��Ҫת�͵�����ñ�������ܷ���.
 * �������������ʹ��Apache Jarkarta Commons BeanUtils
 */

public class PrivatePropertyUtils {


    /**
     * ��ȡ��ǰ�������private/protected��
     */
    static public Object getPrivateProperty(Object object, String propertyName) throws IllegalAccessException, NoSuchFieldException {
        Assert.notNull(object);
        Assert.hasText(propertyName);
        Field field = object.getClass().getDeclaredField(propertyName);
        field.setAccessible(true);
        return field.get(object);
    }

    /**
     * ���õ�ǰ�������private/protected��
     */
    static public void setPrivateProperty(Object object, String propertyName, Object newValue) throws IllegalAccessException, NoSuchFieldException {
        Assert.notNull(object);
        Assert.hasText(propertyName);

        Field field = object.getClass().getDeclaredField(propertyName);
        field.setAccessible(true);
        field.set(object, newValue);
    }

    /**
     * ���õ�ǰ�������private/protected����
     */
    @SuppressWarnings("unchecked")
    static public Object invokePrivateMethod(Object object, String methodName, Object[]params) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Assert.notNull(object);
        Assert.hasText(methodName);
        Class[] types = new Class[params.length];
        for (int i = 0; i < params.length; i++) {
            types[i] = params[i].getClass();
        }
        Method method = object.getClass().getDeclaredMethod(methodName, types);
        method.setAccessible(true);
        return method.invoke(object, params);
    }

    /**
     * ���õ�ǰ�������private/protected����
     */
    static public Object invokePrivateMethod(Object object, String methodName, Object param) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        return invokePrivateMethod(object, methodName, new Object[]{param});
    }
}
